const mysql = require('mysql2');
const fs = require('fs');
const path = require('path');

// 数据库配置
const db = mysql.createPool({
  host: process.env.DB_HOST || 'localhost',
  user: process.env.DB_USER || 'root',
  password: process.env.DB_PASSWORD || 'zds030212',
  database: process.env.DB_NAME || 'case',
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
});

// 初始化数据库表结构
const initDb = async () => {
  try {
    // 先删除已有表，重新创建（开发环境使用）
    // await db.promise().query(`DROP TABLE IF EXISTS health_cards`);
    
    // 创建健康证表
    await db.promise().query(`
      CREATE TABLE IF NOT EXISTS health_cards (
        id INT AUTO_INCREMENT PRIMARY KEY,
        unique_id VARCHAR(50) NOT NULL UNIQUE,
        name VARCHAR(100) NOT NULL,
        gender VARCHAR(10) NOT NULL,
        id_number VARCHAR(50) NOT NULL,
        birth_date DATE,
        work_unit VARCHAR(255) NOT NULL,
        job_title VARCHAR(100) NOT NULL,
        issue_date DATE NOT NULL,
        expiry_date DATE NOT NULL,
        record_number VARCHAR(50),
        photo_url MEDIUMTEXT,
        qrcode_url MEDIUMTEXT,
        stamp_url MEDIUMTEXT,
        age INT,
        type VARCHAR(50),
        result VARCHAR(50) DEFAULT '合格',
        hospital VARCHAR(255),
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
      )
    `);
    console.log('数据库表初始化成功');
    
    // 检查是否需要更改列类型
    try {
      await db.promise().query(`
        ALTER TABLE health_cards 
        MODIFY photo_url MEDIUMTEXT,
        MODIFY stamp_url MEDIUMTEXT,
        MODIFY qrcode_url MEDIUMTEXT,
        MODIFY record_number VARCHAR(50) NULL
      `);
      console.log('已更新表字段类型');
    } catch (alterErr) {
      console.log('表字段更新跳过或失败:', alterErr.message);
    }
    
  } catch (err) {
    console.error('初始化数据库失败:', err);
  }
};

// 在导出前尝试初始化数据库
initDb();

module.exports = db; 